import Router from "koa-router";
import db from '../database/index.js'
import { tokenConfig, blackTokenList } from '../database/config.js'
import jwt from "jsonwebtoken";

const router = new Router();

// id 为可选参数
router.get("/:id?", (ctx, next) => {
    const userId = ctx.params.id;
    ctx.body = "routes/users.js --> get --> /" + `, 参数id:  ${userId}`;
});

/**
 * 登录
 * POST /login
 * @param {string} username 用户名
 * @param {string} password 密码
 * 测试代码见 test.html
 */
router.post("/login", async (ctx, next) => {
    const { username, password } = ctx.request.body;
    const sql = `SELECT * FROM users WHERE username = ?`;
    const [rows] = await db.execute(sql, [username]);
    if (rows.length) {
        const item = rows[0];
        if (item.password === password) {
            const { secret, expiresIn } = tokenConfig;
            const token = jwt.sign({ username }, secret, { expiresIn });
            ctx.body = {
                success: true,
                message: "登录成功",
                data: {
                    token
                }
            }
        } else {
            ctx.body = {
                success: false,
                message: "用户名或密码错误"
            }
        }
    } else {
        ctx.body = {
            success: false,
            message: "用户名未注册"
        }
    }
});

/**
 * register
 * */
router.post('/register', async (ctx) => {
    const { username, password, email } = ctx.request.body;
    const [userList] = await db.execute(`select * from users where username = ?`, [username]);
    if (userList.length) {
        ctx.body = {
            success: false,
            message: '用户名已存在',
            data: null
        };
        return;
    };
    const [rows] = await db.execute(`insert into users (username, password, email) values (?, ?, ?)`, [username, password, email]);
    if (rows.affectedRows) {
        ctx.body = {
            message: '注册成功', success: true,
            data: rows[0]
        };
    } else {
        ctx.body = {
            message: '注册失败', success: false,
            data: null
        };
    }
});

/**
 * 获取用户信息
 * POST /userInfo
 * 测试代码见 test.html
 */
const getUserInfo = async (ctx, isAllUser = false) => {
    const { authorization } = ctx.request.header;
    if (!authorization) {
        ctx.body = {
            success: false,
            message: "缺少授权头"
        }
        return;
    }
    const token = authorization.split(' ')[1];
    if (!token) {
        ctx.body = {
            success: false,
            message: "请先登录"
        }
        return;
    }
    const { secret } = tokenConfig;
    const { username } = jwt.verify(token, secret);
    let rows = [];
    if (isAllUser) {
        const sql = `SELECT * FROM users`;
        [rows] = await db.execute(sql, []);
    } else {
        const sql = `SELECT * FROM users WHERE username = ?`;
        [rows] = await db.execute(sql, [username]);
    }
    if (rows.length) {
        ctx.body = {
            success: true,
            message: "获取用户信息成功",
            data: rows.map(o => {
                delete o.password;
                return o;
            })
        }
    } else {
        ctx.body = {
            success: false,
            message: "用户不存在"
        }
    }
}
router.post("/userInfo", async (ctx, next) => {
    await getUserInfo(ctx)
});
router.post("/userList", async (ctx, next) => {
    await getUserInfo(ctx, true)
});

/**
 * delUser
 * */
router.post('/del', async (ctx) => {
    const { id } = ctx.request.body;
    const [rows] = await db.execute(`delete from users where id = ?`, [id]);
    if (rows.affectedRows) {
        ctx.body = {
            message: '注销成功', success: true,
            data: rows[0]
        };
    } else {
        ctx.body = {
            message: '注销失败', success: false,
            data: null
        };
    }
});

/**
 * 登出
 * POST /logout
 * 测试代码见 test.html
 */
router.post("/logout", async (ctx, next) => {
    const { authorization } = ctx.request.header;
    if (!authorization) {
        ctx.body = {
            success: false,
            message: "缺少授权头"
        }
        return;
    }
    const token = authorization.split(' ')[1];
    if (!token) {
        ctx.body = {
            success: false,
            message: "请先登录"
        }
        return;
    }
    blackTokenList.add(token);
    ctx.body = {
        success: true,
        message: "退出登录成功",
        data: null
    }
});

export default router;
